// 公共接口调用方法封装，支持 Promise
const { tipToast } = require('./env');
const { getUserToken } = require('../biztools/wex');

// 格式化错误信息
const formatMsg = (msg) => {
    const prefix = [
        /\n*/gi,
        /.*服务端错误\:/gi,
        /.*微信支付错误码\:/gi,
        /.*错误描述\:/gi,
        /.*品牌侧.*\:/gi,
        /.*商品(侧|库).*\:/gi,
        /.*仓库侧.*\:/gi,
        /.*库存不足\:/gi,
        /\:rpc error: code.*/gi,
        /\s*/gi,
    ];
    prefix.forEach(i => {
        msg = msg.replace(i, '');
    });
    return msg;
};

// ajax
const ajax = (url, param, method, isAuth = true, header = {}, showError = true) => {
    const token = getUserToken();
    let _header = {
        'content-type': 'application/json',
    };
    if (isAuth) {
        _header = {
            ..._header,
            token,
        };
    }
    return new Promise((reslove, reject) => {
        if (isAuth && !token) reject(false);
        wx.request({
            url,
            method,
            timeout: 10000,
            data: {
              ...param,
            },
            header: {
                ...header,
                ..._header,
            },
            success (res) {
                const { success, message, error_code, error_message } = res.data;
                if (success === false) {
                    if (showError && res.data.msg) tipToast(formatMsg(res.data.msg));
                    // if (res.data.alert) tipToast(res.data.alert);
                    reslove(false);
                } else if (error_code || error_message || (message && message.toLocaleLowerCase() != 'success')) {
                    if (showError) tipToast(error_message || message);
                    reslove(false);
                } else {
                    reslove(res.data);
                }
            },
            fail (err) {
                reject(err);
            },
        })
    });
};

module.exports = {
    get: (url, param, showError = true) => {
        return ajax(url, param, 'GET', true, {}, showError);
    },
    getNormal: (url, param, header) => {
        return ajax(url, param, 'GET', false, header);
    },
    post: (url, param, showError = true) => {
        return ajax(url, param, 'POST', true, {}, showError);
    },
    postNormal: (url, param, header) => {
        return ajax(url, param, 'POST', false, header);
    },
    put: (url, param) => {
        return ajax(url, param, 'PUT');
    },
    putNormal: (url, param, header) => {
        return ajax(url, param, 'PUT', false, header);
    },
    del: (url, param) => {
        return ajax(url, param, 'DELETE');
    },
    delNormal: (url, param, header) => {
        return ajax(url, param, 'DELETE', false, header);
    },
    patch: (url, param) => {
        return ajax(url, param, 'PATCH');
    },
};
